package com.sunmouse.toolkit.fragment.media;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;

import com.sunmouse.toollib.utils.StringUtils;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toollib.utils.system.SystemUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.adapter.MessageAdapter;
import com.sunmouse.toolkit.bean.MessageBean;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.util.ChatUtil;
import com.sunmouse.toolkit.widget.menu.DragLayout;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChatFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener{


    @BindView(R.id.chat_list)
    ListView chatList;
    @BindView(R.id.input_et)
    EditText inputEt;
    @BindView(R.id.send_btn)
    Button sendBtn;
    @BindView(R.id.input_container)
    RelativeLayout inputContainer;
    @BindView(R.id.server_sw)
    Switch serverSw;
    @BindView(R.id.client_sw)
    Switch clientSw;
    @BindView(R.id.m_drawer)
    DragLayout mDrawer;
    Unbinder unbinder;


    private MessageAdapter mAdapter;
    private ArrayList<MessageBean> messages;
    private String mName;

    private ChatUtil mUtil;
    private String msg;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_chat, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void init() {
        this.serverSw.setOnCheckedChangeListener(this);
        this.clientSw.setOnCheckedChangeListener(this);
        this.sendBtn.setOnClickListener(this);
        this.mDrawer.setOnStatusChangedListener(new OnDrawerHandler());

        mName = ChatUtil.generateName();
        mUtil = ChatUtil.getInstance(mName);
        mUtil.setOnMessageListener(new OnMessageResponse());

        messages = new ArrayList<>();
        mAdapter = new MessageAdapter(messages, getActivity());
        chatList.setAdapter(mAdapter);

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == serverSw && isChecked) {
            mUtil.launchServer(ChatUtil.PORT);
        } else if (buttonView == clientSw) {
            if (isChecked)
                mUtil.launchClient(ChatUtil.SERVER, ChatUtil.PORT);
            else
                mUtil.disconnect();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.send_btn:
                if (!mUtil.isClientLaunched()) {
                    ToastUtils.simpleToast(getActivity(), "please launch client first");
                    return;
                }
                msg = inputEt.getText().toString();
                if (StringUtils.isEmpty(msg)) return;
                mUtil.sendMessage(msg);
                inputEt.setText("");//clear sent msg
                break;
        }
    }

    /**
     * handle message here
     */
    private class OnMessageResponse implements ChatUtil.OnMessageListener {
        @Override
        public void onMessage(String msg) {
//            LogUtils.d("----------receive--" + msg);
            String[] res = msg.split("#");
            // LogUtils.d("----------from--" + res[0]+"   mName="+mName+" :"+res[0].length()+" "+mName.length());

            MessageBean bean = new MessageBean();
            bean.setTime(StringUtils.SDF.format(new Date(System.currentTimeMillis())));
            bean.setMsg(msg);
            bean.setFrom(res[0].equals(mName) ? MessageBean.From.ME : MessageBean.From.OTHER);
            messages.add(bean);

            mAdapter.notifyDataSetChanged();
            chatList.smoothScrollToPosition(messages.size() - 1);
        }

        @Override
        public void onError(Exception e) {

        }
    }

    /**
     * draw listener
     */
    private class OnDrawerHandler implements DragLayout.OnStatusChangedListener {

        @Override
        public void onStatusChanged(boolean isOpened) {
            if (isOpened) {
                SystemUtils.closeKeyboard(getActivity());
                serverSw.requestFocus();
            }
        }
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mUtil.disconnect();

    }
}
